package org.ojudge.ojudgecodesandbox.sandbox.template;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.ojudge.ojudgecodesandbox.modal.ExecuteCodeRequest;
import org.ojudge.ojudgecodesandbox.modal.ExecuteCodeResponse;
import org.ojudge.ojudgecodesandbox.modal.ExecuteMessage;
import org.ojudge.ojudgecodesandbox.modal.JudgeInfo;
import org.ojudge.ojudgecodesandbox.sandbox.CodeSandbox;
import org.ojudge.ojudgecodesandbox.utils.ProcessUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Java代码沙箱实现模板
 */
@Slf4j
public abstract class JavaCodeSandboxTemplate implements CodeSandbox {

    private static final String GLOBAL_CODE_PATH = "tempCode";

    private static final String GLOBAL_JAVA_CLASS_PATH = "Main.java";

    private static final long TIME_OUT = 5000;

    private static final String SECURITY_MANAGER_PATH = "E:\\Programme\\Code\\Project\\oJudge\\oJudge-code-sandbox\\src\\main\\resources\\security\\MySecurityManager.class";

    private static final String SECURITY_MANAGER_CLASS_NAME = "MySecurityManager";


    /**
     * 执行代码
     *
     * @param request
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {
        List<String> inputList = request.getInputList();
        String code = request.getCode();
        String language = request.getLanguage();

        // 1.把用户的代码隔离存放为文件
        File userCodeFile = saveCodeToFile(code);

        // 2.编译代码
        ExecuteMessage compileFileExecuteMessage = compileFile(userCodeFile);
        log.info("编译信息:{}", compileFileExecuteMessage);

        // 3.执行代码
        List<ExecuteMessage> executeMessageList = runCode(userCodeFile, inputList);

        // 4.收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = getOutputResponse(executeMessageList);

        // 5.文件清理
        boolean deleteFile = deleteFile(userCodeFile);
        if (!deleteFile) {
            log.error("文件清理失败,userCodeFilePath={}", userCodeFile.getAbsolutePath());
        }
        return executeCodeResponse;
    }

    /**
     * 1.把用户的代码隔离存放为文件
     *
     * @param code
     * @return
     */
    public File saveCodeToFile(String code) {
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_PATH;//注意使用File.separator保证不同操作系统环境同样能运行
        //判断全局代码目录是否存在,没有就新建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        // 把用户的代码隔离存放为文件
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_PATH;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        return userCodeFile;
    }

    /**
     * 2.编译代码
     *
     * @return
     */
    public ExecuteMessage compileFile(File userCodeFile) {
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcess(compileProcess, "编译");
            if (executeMessage.getExitValue() != 0) {
                throw new RuntimeException("编译错误");
            }
            return executeMessage;
        } catch (IOException e) {
            log.error("Java代码编译错误");
            //TODO抛出异常处理
            throw new RuntimeException(e);
        }
    }

    /**
     * 3.运行代码,获得执行结果列表
     *
     * @param userCodeFile 用户代码文件
     * @param inputList
     * @return 运行结果列表
     */
    public List<ExecuteMessage> runCode(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParent();
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (int i = 0; i < inputList.size(); i++) {//运行所有的输入样例
            StopWatch stopWatch = new StopWatch();
//            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=%s Main %s", userCodeParentPath, SECURITY_MANAGER_PATH, SECURITY_MANAGER_CLASS_NAME, inputList.get(i));
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputList.get(i));
            try {
                stopWatch.start();
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                //进程超时限制
                //todo可以尝试优化,判断进程是否正常运行
                new Thread(() -> {
                    try {
                        //线程睡眠
                        Thread.sleep(TIME_OUT);
                        //当线程睡眠后,进程还没有结束,则强制结束进程
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
//                ExecuteMessage executeMessage = ProcessUtils.runProcess(runProcess, "运行");
                ExecuteMessage executeMessage = ProcessUtils.runInteractProcess(runProcess, "运行", inputList.get(i));
                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);
            } catch (Exception e) {
                throw new RuntimeException("程序执行异常");
            }
        }
        return executeMessageList;
    }

    /**
     * 4.收集,整理,获取 输出结果
     *
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        //取用时最大值,便于判断是否超时
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                //执行中存在错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        //正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        executeCodeResponse.setStatus(1);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);

        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }

    /**
     * 5.文件清理
     *
     * @param userCodeFile
     * @return
     */
    public boolean deleteFile(File userCodeFile) {
        if (userCodeFile.getParent() != null) {
            boolean del = FileUtil.del(userCodeFile.getParent());
            log.info("程序运行完成,删除文件{}", (del ? "成功" : "失败"));
            return del;
        }
        return true;
    }


    /**
     * 获取错误响应
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(2);//表示代码沙箱错误
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;

    }
}
